﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using BMServiceGenerator.Extensions;

namespace BMServiceGenerator
{
    public static class FolderFileManager
    {
        public static string SetupTempFolder(Arguments arguments)
        {
            const string tempFolderPath = "Temp";

            if (Directory.Exists(tempFolderPath))
            {
                Directory.Delete(tempFolderPath, true);
            }

            var fullTempFolderPath = Directory.CreateDirectory(tempFolderPath).FullName;

            Directory.CreateDirectory(tempFolderPath + @"\bin");

            File.Copy(@"Web.config.template", string.Concat(tempFolderPath, @"\", "Web.config"));

            using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream("BMServiceGenerator.Resources.Microsoft.BizTalk.Bam.EventObservation.dll"))
            {
                using (
                    Stream output =
                        File.Create(string.Concat(tempFolderPath, @"\", "Microsoft.BizTalk.Bam.EventObservation.dll")))
                {
                    input.CopyStream(output);
                }
            }

            return fullTempFolderPath;
        }

        public static void SetupOutputFolder(Arguments arguments)
        {
            if (Directory.Exists(arguments.OutputFolder))
            {
                Directory.Delete(arguments.OutputFolder, true);
            }
            Directory.CreateDirectory(arguments.OutputFolder);
        }

        internal static void DeployToOutput(Arguments arguments)
        {
            new DirectoryInfo(arguments.TempFolder + @"\bin").ShallowCopy(arguments.OutputFolder + @"\bin\");

            new DirectoryInfo(arguments.TempFolder).CopyFilesWithExtension("*.svc", new DirectoryInfo(arguments.OutputFolder));

            File.Copy(string.Concat(arguments.TempFolder, @"\", "Web.config"), string.Concat(arguments.OutputFolder + @"\", "Web.config"));
        }
    }
}
